package com.vx.vxbug.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.vx.vxbug.entities.Bug;

@Repository("bugDao")
public class SqlBugDao implements IBugDao {

    @PersistenceContext
    private EntityManager entityManager;

    @Transactional(propagation = Propagation.REQUIRED)
    public void addBug(Bug b) {
        entityManager.persist(b);

    }

    @Transactional(propagation = Propagation.REQUIRED)
    public Bug getBugById(int id) {
        return entityManager.find(Bug.class, id);
    }

    @SuppressWarnings("unchecked")
    @Transactional(propagation = Propagation.REQUIRED)
    public List<Bug> getAllBugsForProgramId(int programId) {
        List<Bug> result = entityManager.createQuery("FROM Bug as b WHERE b.programId = :_id").setParameter("_id", programId)
                .getResultList();
        return result;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void updateBug(Bug b) {

//        Bug a = entityManager.find(Bug.class, b.getId());
//        entityManager.detach(a);
//        a = b;
        entityManager.merge(b);
//		entityManager.persist(a);

    }

    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteBug(Bug b) {
        entityManager.remove(b);

    }

    public SqlBugDao() {
        super();
    }

}
